package cn.moningxi.controller;

import cn.moningxi.bean.*;
import cn.moningxi.service.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;


@Controller
@SessionAttributes(value = "onlineUser", types = String.class)
public class CustomerInfomationController {
    @Autowired
    CustomerInfomationService customerInfomationService;
    @Autowired
    CConsigneeService cConsigneeService;
    @Autowired
    CPointLogService cPointLogService;
    @Autowired
    CustomerLoginLogService customerLoginLogService;
    @Autowired
    CBalanceLogService cBalanceLogService;

    /**
     * 返回个人信息修改界面
     *
     * @param mv
     * @param request
     * @return
     */
    @RequestMapping("/cntApi/info")
    public ModelAndView info(ModelAndView mv, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUserById(onlineUser.getCustomerInfoId());
        mv.addObject("onlineUser", onlineUser);
        mv.setViewName("business/person/information");
        return mv;
    }

    /**
     * 更新当前用户个人信息
     *
     * @param mv
     * @param
     * @return
     */
    @RequestMapping(value = "/cntApi/updateUserInfo", method = RequestMethod.POST)
    public ModelAndView updateUser(ModelAndView mv, CustomerInfomation onlineUser) {
        customerInfomationService.updateUser(onlineUser);
        mv.setViewName("redirect:/cntApi/info");
        return mv;
    }

    /**
     * 用户更改密码
     *
     * @param mv
     * @param customerInfoId
     * @param oldp
     * @param newp
     * @return
     */
    @RequestMapping(value = "/cntApi/updateUserPwd", method = RequestMethod.POST)
    public ModelAndView updateUserpassowrd(ModelAndView mv, @RequestParam("customerInfoId") String customerInfoId, @RequestParam("oldp") String oldp, @RequestParam("newp") String newp) {
        Boolean flag = customerInfomationService.updateUserPwd(customerInfoId, oldp, newp);
        mv.addObject("flag", flag);
        mv.setViewName("business/person/password");
        return mv;
    }

    /**
     * 更改密码界面
     *
     * @param mv
     * @return
     */
    @RequestMapping(value = "/cntApi/PwdPage")
    public ModelAndView passowrd(ModelAndView mv, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);
        mv.addObject("onlineUser", onlineUser);
        mv.setViewName("business/person/password");
        return mv;
    }

    /**
     * 跳转安全界面
     *
     * @param mv
     * @param request
     * @return
     */
    @RequestMapping(value = "/cntApi/SafetyPage")
    public ModelAndView SafetyPage(ModelAndView mv, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);
        mv.addObject("onlineUser", onlineUser);
        mv.setViewName("business/person/safety");
        return mv;
    }


    /**
     * 地址查看
     *
     * @param mv
     * @param request
     * @return
     */
    @RequestMapping(value = "cntApi/consignee")
    public ModelAndView showAddress(ModelAndView mv, HttpServletRequest request) {

        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);
        List<CConsignee> consignees = cConsigneeService.addrShow(onlineUser);

        mv.addObject("onlineUser", onlineUser);
        mv.addObject("consignees", consignees);
        mv.setViewName("business/person/address");
        return mv;
    }

    /**
     * 添加用户地址
     *
     * @param mv
     * @param
     * @return
     */
    @RequestMapping(value = "cntApi/addConsignee", method = RequestMethod.POST)
    public ModelAndView addConsignee(ModelAndView mv, CConsignee consignee, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);
        cConsigneeService.addaddr(onlineUser, consignee);

        mv.setViewName("redirect:/cntApi/consignee");
        return mv;
    }

    /**
     * 删除地址
     *
     * @param mv
     * @param caId
     * @return
     */
    @RequestMapping(value = "cntApi/delConsignee")
    public ModelAndView delConsignee(ModelAndView mv, Integer caId) {

        cConsigneeService.deladdr(caId);

        mv.setViewName("redirect:/cntApi/consignee");
        return mv;
    }

    /**
     * 返回修改界面
     *
     * @param mv
     * @param caId
     * @return
     */
    @RequestMapping(value = "cntApi/consigneeByAdd")
    public ModelAndView consigneeByAdd(ModelAndView mv, HttpServletRequest request, Integer caId) {
        CConsignee consignee = cConsigneeService.queryAddById(caId);

        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);
        mv.addObject("onlineUser", onlineUser);
        mv.addObject("consignee", consignee);
        mv.setViewName("business/person/addressedit");
        return mv;
    }

    /**
     * 更新地址
     *
     * @param mv
     * @param request
     * @param consignee
     * @return
     */
    @RequestMapping(value = "cntApi/consigneeEditByAdd")
    public ModelAndView consigneeEditByAdd(ModelAndView mv, HttpServletRequest request, CConsignee consignee) {
        boolean ret = cConsigneeService.updateAddById(consignee);
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);
        mv.addObject("onlineUser", onlineUser);
        mv.addObject("consignee", consignee);
        mv.setViewName("redirect:/cntApi/consignee");
        return mv;
    }

    /**
     * 设置默认地址
     *
     * @param mv
     * @param customerAddrId
     * @param request
     * @return
     */
    @RequestMapping(value = "cntApi/isDefaultAddr")
    public ModelAndView isDefaultAddr(ModelAndView mv, Integer customerAddrId, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        cConsigneeService.isDefaultAddr(customerAddrId, onlineUser);
        mv.setViewName("redirect:/cntApi/consignee");
        return mv;
    }

    /**
     * 查看积分
     *
     * @param mv
     * @param request
     * @return
     */
    @RequestMapping(value = "cntApi/points")
    public ModelAndView points(ModelAndView mv, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);

        List<CPointLog> points = cPointLogService.queryPointList(onlineUser);
        Integer signIn = cPointLogService.isPoint(onlineUser, 5);

        mv.addObject("points", points);
        mv.setViewName("business/person/points");
        return mv;
    }

    /**
     * 签到积分
     *
     * @param mv
     * @param request
     * @param userPoint
     * @return
     */
    @RequestMapping(value = "cntApi/addPoint")
    public ModelAndView addPoint(ModelAndView mv, HttpServletRequest request, Integer userPoint) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");

        Integer signIn = cPointLogService.addPoint(onlineUser, userPoint);
        mv.addObject("signIn", signIn);

        mv.setViewName("redirect:/cntApi/points");
        return mv;
    }

    /**
     * 余额查看
     *
     * @param mv
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "cntApi/balance")
    public ModelAndView balance(ModelAndView mv, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        System.out.println(onlineUser.getCustomerId());
        mv.addObject("onlineUser", onlineUser);
        mv.setViewName("business/person/wallet");
        return mv;
    }

    /**
     * 余额明细
     *
     * @param mv
     * @param request
     * @param
     * @return
     */
    @RequestMapping(value = "cntApi/balancelist")
    public ModelAndView balanceList(ModelAndView mv, HttpServletRequest request) {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        onlineUser = customerInfomationService.queryUser(onlineUser);
        List<CBalanceLog> balances = cBalanceLogService.queryBal(onlineUser);
        mv.addObject("onlineUser", onlineUser);
        mv.addObject("balances", balances);
        mv.setViewName("business/person/walletlist");
        return mv;
    }

    @RequestMapping(value = "cntApi/myBill")
    public ModelAndView myBill(ModelAndView mv, HttpServletRequest request) {

        mv.setViewName("business/person/bill");
        return mv;
    }

    @RequestMapping(value = "cntApi/myBillList")
    public ModelAndView myBilllist(ModelAndView mv, HttpServletRequest request) {

        mv.setViewName("business/person/billlist");
        return mv;
    }

    /**
     * 作用：使用邮箱的方式注册客户
     *
     * @param mv
     * @param cu
     * @return
     */
    @RequestMapping("/cntApi/register")
    @ResponseBody
    public ModelAndView register(ModelAndView mv, CustomerInfomation cu) {
        boolean flag = customerInfomationService.register(cu);
        if (flag == true) {
            cu = customerInfomationService.queryByEmail(cu);
            mv.addObject("errMessage", null);
            mv.addObject("onlineUser", cu);
            mv.setViewName("redirect:/cntApi/info");
        } else {
            mv.addObject("cu", cu);
            mv.addObject("errMessage", "邮箱已存在！");
            mv.setViewName("business/home/register");
        }
        return mv;
    }

    /**
     * 用户登录校验
     *
     * @param mv
     * @param cu
     * @return
     */
    @RequestMapping(value = "/cntApi/login", method = RequestMethod.POST)
    public ModelAndView login(ModelAndView mv, CustomerInfomation cu, HttpServletRequest request) {
        CustomerInfomation customerInfomation;
        customerInfomation = customerInfomationService.queryByEmail(cu);
        if (customerInfomation != null && cu.getEmai().equals(customerInfomation.getEmai()) && cu.getPassword().equals(customerInfomation.getPassword())) {
            CustomerLoginLog customerLoginLog;
            //账号正常
            if ("1".equals(customerInfomation.getCustomerStatus())) {
                customerLoginLog = new CustomerLoginLog(null, customerInfomation.getCustomerId(), LocalDateTime.now(), request.getRemoteAddr(), 1);
                mv.addObject("errMsg", null);
                mv.addObject("onlineUser", customerInfomation);
                mv.setViewName("redirect:/index/init");
            } else {
                //账号异常
                customerLoginLog = new CustomerLoginLog(null, customerInfomation.getCustomerId(), LocalDateTime.now(), request.getRemoteAddr(), 0);
                mv.addObject("cu", customerInfomation);
                mv.addObject("errMsg", "账号已冻结！");
                mv.setViewName("business/home/login");
            }
            customerLoginLogService.insert(customerLoginLog);
        } else {
            mv.addObject("cu", cu);
            mv.addObject("errMsg", "邮箱或者密码错误请重新输入");
            mv.setViewName("business/home/login");
        }
        return mv;
    }

    /**
     * 查询未删除的customer的信息详情
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping("/MemberApi/queryMembers")
    public ModelAndView queryMembers(ModelAndView modelAndView) {
        List<CustomerInfomation> customerInfomationList = customerInfomationService.queryMembers();
        modelAndView.addObject("customers", customerInfomationList);
        modelAndView.setViewName("backstage/member-list");
        return modelAndView;
    }

    /**
     * 查询已删除的customer的信息详情
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping("/MemberApi/queryDelMembers")
    public ModelAndView queryDelMembers(ModelAndView modelAndView) {
        List<CustomerInfomation> customerInfomationList = customerInfomationService.queryDelMembers();
        modelAndView.addObject("customers", customerInfomationList);
        modelAndView.setViewName("backstage/member-del");
        return modelAndView;
    }

    /**
     * 根据customerInfoId删除customer的信息
     *
     * @param modelAndView
     * @param customerInfoId
     * @return
     */
    @RequestMapping("/MemberApi/removeMembers/{customerInfoId}")
    public ModelAndView removeMember(ModelAndView modelAndView, @PathVariable("customerInfoId") Integer customerInfoId) {
        customerInfomationService.removeMember(customerInfoId);
        modelAndView.setViewName("redirect:/MemberApi/queryMembers");
        return modelAndView;
    }

    /**
     * 将删除的customer还原
     *
     * @param modelAndView
     * @param customerInfoId
     * @return
     */
    @RequestMapping("/MemberApi/returnMembers/{customerInfoId}")
    public ModelAndView returnMember(ModelAndView modelAndView, @PathVariable("customerInfoId") Integer customerInfoId) {
        customerInfomationService.returnMember(customerInfoId);
        modelAndView.setViewName("redirect:/MemberApi/queryDelMembers");
        return modelAndView;
    }

    /**
     * 根据customerInfoId和customerStatus来修改用户账号状态
     * 若该账号冻结，则为其解冻；若账号正常，则将其冻结。
     */
    @RequestMapping("/MemberApi/editMembers/{customerInfoId}/{customerStatus}")
    public ModelAndView editMembers(ModelAndView modelAndView, @PathVariable("customerInfoId") Integer customerInfoId, @PathVariable("customerStatus") String customerStatus) {
        customerInfomationService.editMembers(customerInfoId, customerStatus);
        modelAndView.setViewName("redirect:/MemberApi/queryMembers");
        return modelAndView;
    }

    /**
     * 查询出全部消费者的会员等级、积分等信息
     *
     * @param modelAndView
     * @return
     */
    @RequestMapping("/MemberApi/selectCustomerLevel")
    public ModelAndView selectCustomerLevel(ModelAndView modelAndView) {
        List<CustomerInfomation> customerInfomations = customerInfomationService.selectCustomerLevel();
        modelAndView.addObject("customerInfomations", customerInfomations);
        modelAndView.setViewName("backstage/CustomersLevelInformation");
        return modelAndView;
    }

    /**
     * 退出登录
     *
     * @param mv
     * @return
     */
    @RequestMapping(value = "cntApi/loginOut")
    public ModelAndView loginOut(ModelAndView mv, SessionStatus sessionStatus) {
        sessionStatus.setComplete();
        mv.setViewName("business/home/login");
        return mv;
    }

    /**
     * 上传头像
     *
     * @param mv
     * @param headUrl
     * @return
     */
    @RequestMapping("cntApi/uploadHeadUrl")
    public ModelAndView uploadHeadUrl(ModelAndView mv, String headUrl, HttpServletRequest request) throws IOException {
        CustomerInfomation onlineUser = (CustomerInfomation) request.getSession().getAttribute("onlineUser");
        String suffix = headUrl.substring(headUrl.lastIndexOf("."));
        if (".png.jpg.jpeg.gif".contains(suffix.toLowerCase())) {
            customerInfomationService.updateUserheadUrl(onlineUser.getCustomerId(), headUrl);
            onlineUser = customerInfomationService.queryUser(onlineUser);
            mv.addObject("onlineUser", onlineUser);
            mv.setViewName("redirect:/cntApi/info");
        } else {
            //图片格式错误
            mv.setViewName("business/403");
        }
        return mv;
    }
}
